package com.googlecode.cswish.struts.hibernate;

import org.hibernate.mapping.Column;
import org.hibernate.mapping.Property;
import org.hibernate.type.Type;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.googlecode.cswish.util.XMLUtil;

public class MappingManager {
	
	public static void updateClassMapping( 
			DynamicModelDef dynamicModelDef) {
		try {
			String entityName = dynamicModelDef.getEntityName();
			String file = MappingManager.class.getResource(
					entityName + ".hbm.xml").getPath();

			Document document = XMLUtil.loadDocument(file);
			NodeList componentTags = document
					.getElementsByTagName("dynamic-component");
			Node node = componentTags.item(0);
			XMLUtil.removeChildren(node);

			// FIXME:
//			Iterator propertyIterator = dynamicModelDef.getCustomProperties()
//					.getPropertyIterator();
//			while (propertyIterator.hasNext()) {
//				Property property = (Property) propertyIterator.next();
//				Element element = createPropertyElement(document, property);
//				node.appendChild(element);
//			}

			XMLUtil.saveDocument(document, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Document updateClass(Document document, String entityName, String tableName) {
		NodeList classNodeList = document.getElementsByTagName("class");
		Node classNode = classNodeList.item(0);
		NamedNodeMap nodeMap = classNode.getAttributes();
		nodeMap.getNamedItem("entity-name").setNodeValue(entityName);
		nodeMap.getNamedItem("table").setNodeValue(tableName);
		return document;
	}

	public static Element addProperty(Document document, Property property) {
		Element element = document.createElement("property");
		Type type = property.getType();

		element.setAttribute("name", property.getName());
		element.setAttribute("column", ((Column) property.getColumnIterator()
				.next()).getName());
		element.setAttribute("type", type.getReturnedClass().getName());
		element.setAttribute("not-null", String.valueOf(false));

		return element;
	}
}